package com.xinchao.service.impl;

import com.google.common.collect.Maps;
import com.xinchao.core.constant.ModuleConstant;
import com.xinchao.core.util.FileUtils;
import com.xinchao.core.util.HuaWeiCloudUtils;
import com.xinchao.dao.BreakdownImgMapper;
import com.xinchao.dao.DeviceMapper;
import com.xinchao.model.BreakdownImg;
import com.xinchao.model.vo.DeviceDetailVO;
import com.xinchao.service.BreakdownImgService;
import com.xinchao.service.OperationLogService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 终端故障图片
 *
 * @author linqiang
 * @date 2018-08-08 17:34
 */
@Service("breakdownImgService")
public class BreakdownImgServiceImpl implements BreakdownImgService {

    @Autowired
    private BreakdownImgMapper breakdownImgMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private OperationLogService operationLogService;

    @Autowired
    private  HuaWeiCloudUtils huaWeiCloudUtils;

    /**
     * @param deviceCode 终端唯一设备编码
     * @return
     */
    @Override
    public List<BreakdownImg> list(String deviceCode) {
        return breakdownImgMapper.list(deviceCode);
    }

    /**
     * 新增故障图片
     *
     * @param deviceId 终端ID
     * @param files    故障图片文件
     * @param request  请求
     * @return 图片ID, URL
     * @throws IOException
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> save(Long deviceId, MultipartFile files, HttpServletRequest request) throws IOException {
        DeviceDetailVO deviceDetail = deviceMapper.getDeviceDetail(deviceId);
        if (null == deviceDetail) {
            return new HashMap<>(1);
        }
        //获取图片原始图片名
        String originalFilename = files.getOriginalFilename();
        //获取图片后缀
        String extension = FilenameUtils.getExtension(originalFilename);
        //没有后缀的图片名
        String fileName = originalFilename.replaceAll("." + extension, "");
        //校验图片名是否存在
        BreakdownImg breakdownImg = breakdownImgMapper.selectByName(deviceDetail.getDeviceCode(), fileName);
        //图片名已存在
        if (breakdownImg != null) {
            //校验文件名是否与库中的同商家的视频文件名重复，如果重复，自动命名文件名，命名规则（a.jpg,a(1).jpg,a(2).jpg）
            //查找类型"a(1)"类似的文件，mysql匹配类型为“a(%)%”
            int count = breakdownImgMapper.countByName(deviceDetail.getDeviceCode(), fileName + "(%)");
            if (count >= 0) {
                fileName = fileName + "(" + (count + 1) + ")";
            }
        }
        //将MultipartFile转化为指定文件名的File
        File file = FileUtils.multipartFileConvertFile(files, fileName + "." + extension);
        //将图片上传至华为云
        String url = huaWeiCloudUtils.uploadFile2HuaweiCloud(file, "breakdownImg/" + deviceId + "/picture/");
        //把MultipartFile转化为File,会在本地创建图片，用完file后，需要删除
        if (file.exists()) {
            file.delete();
        }
        BreakdownImg breakdownImgAdd = new BreakdownImg();
        breakdownImgAdd.setDataStatus(0);
        breakdownImgAdd.setDeviceCode(deviceDetail.getDeviceCode());
        breakdownImgAdd.setImgName(fileName);
        breakdownImgAdd.setImgUrl(url);
        breakdownImgAdd.setAddTime(System.currentTimeMillis());
        breakdownImgMapper.insert(breakdownImgAdd);
        Map<String, Object> pictureMap = Maps.newHashMap();
        pictureMap.put("breakdownImgId", breakdownImgAdd.getBreakdownImgId());
        pictureMap.put("file", url);
        //记录操作日志
        operationLogService.saveSuccessOperationLog("保存故障图片成功，终端ID为：" + deviceId + ",故障图片ID为："
                + breakdownImgAdd.getBreakdownImgId(), ModuleConstant.MODULE_DEVICE_MNG + "-"
                + ModuleConstant.MODULE_BREAKDOWN_IMG_MNG, request);
        return pictureMap;
    }

    /**
     * 根据主键删除故障图片
     *
     * @param breakdownImgId 故障图片ID
     * @param request        请求
     * @return 影响行数
     */
    @Override
    public int deleteByPrimaryKey(Long breakdownImgId, HttpServletRequest request) {
        int row = breakdownImgMapper.deleteByPrimaryKey(breakdownImgId);
        operationLogService.saveSuccessOperationLog("删除故障图片成功，故障图片ID为：" + breakdownImgId,
                ModuleConstant.MODULE_DEVICE_MNG + "-" + ModuleConstant.MODULE_BREAKDOWN_IMG_MNG, request);
        return row;
    }
}
